package org.example.sec11.interceptors.server;

import io.grpc.*;
import org.example.sec11.Constants;
import org.example.sec11.UserRole;

import java.util.Objects;
import java.util.Set;

public class UserRoleInterceptor implements ServerInterceptor {
    //管理员 所有都能访问
    private static final Set<String> IS_SET = Set.of("1", "2", "3");
    //普通用户 服务端流不允许 其他可以
    private static final Set<String> NOT_SET = Set.of("4", "5", "6");

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
        String token = extractToken(headers.get(Constants.USER_TOKEN_KEY));
        var ctx = toContext(token);
        if (Objects.nonNull(ctx)) {
            return Contexts.interceptCall(ctx, call, headers, next);
        }
        return close(call, headers, Status.PERMISSION_DENIED.withDescription("user is not allowed to do this operation"));
    }

    private <ReqT, RespT> ServerCall.Listener<ReqT> close(ServerCall<ReqT, RespT> call, Metadata headers, Status status) {
        call.close(status, headers);
        return new ServerCall.Listener<ReqT>() {
        };
    }


    private Context toContext(String token) {
        if (Objects.nonNull(token) && (IS_SET.contains(token) || NOT_SET.contains(token))) {
            var role = IS_SET.contains(token) ? UserRole.PRIM : UserRole.STANDED;
            return Context.current().withValue(Constants.USER_ROLE_KEY, role);
        }
        return null;
    }

    private String extractToken(String value) {
        return Objects.nonNull(value) && value.startsWith(Constants.BEARER) ? value.substring(Constants.BEARER.length()).trim() : null;
    }
}
